import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { FundData, MarketData, PaginatedResponse } from '../../types';
import { dataAPI } from '../../services/api';

interface DataState {
  funds: FundData[];
  currentFund: FundData | null;
  fundSearchResults: FundData[];
  marketData: MarketData[];
  marketIndicators: any;
  fundPerformance: any;
  syncStatus: any;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  filters: {
    search?: string;
    fund_type?: string;
    risk_level?: number;
    min_return?: number;
    max_return?: number;
  };
  loading: boolean;
  error: string | null;
}

const initialState: DataState = {
  funds: [],
  currentFund: null,
  fundSearchResults: [],
  marketData: [],
  marketIndicators: null,
  fundPerformance: null,
  syncStatus: null,
  pagination: {
    current: 1,
    pageSize: 20,
    total: 0,
  },
  filters: {},
  loading: false,
  error: null,
};

// 异步actions
export const fetchFunds = createAsyncThunk(
  'data/fetchFunds',
  async (params: {
    search?: string;
    fund_type?: string;
    page?: number;
    page_size?: number;
  } = {}, { rejectWithValue }) => {
    try {
      const response = await dataAPI.getFunds(params);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取基金列表失败');
    }
  }
);

export const fetchFund = createAsyncThunk(
  'data/fetchFund',
  async (fundCode: string, { rejectWithValue }) => {
    try {
      const fund = await dataAPI.getFund(fundCode);
      return fund;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取基金详情失败');
    }
  }
);

export const searchFunds = createAsyncThunk(
  'data/searchFunds',
  async (params: {
    keyword?: string;
    fund_type?: string;
    risk_level?: number;
    min_return?: number;
    max_return?: number;
  }, { rejectWithValue }) => {
    try {
      const response = await dataAPI.searchFunds(params);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '搜索基金失败');
    }
  }
);

export const fetchFundPerformance = createAsyncThunk(
  'data/fetchFundPerformance',
  async ({ fundCode, days }: { fundCode: string; days?: number }, { rejectWithValue }) => {
    try {
      const performance = await dataAPI.getFundPerformance(fundCode, days);
      return performance;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取基金业绩失败');
    }
  }
);

export const fetchMarketData = createAsyncThunk(
  'data/fetchMarketData',
  async (params: {
    indicator_type?: string;
    days?: number;
  } = {}, { rejectWithValue }) => {
    try {
      const marketData = await dataAPI.getMarketData(params);
      return marketData;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取市场数据失败');
    }
  }
);

export const fetchMarketIndicators = createAsyncThunk(
  'data/fetchMarketIndicators',
  async (_, { rejectWithValue }) => {
    try {
      const indicators = await dataAPI.getMarketIndicators();
      return indicators;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取市场指标失败');
    }
  }
);

export const createSyncTask = createAsyncThunk(
  'data/createSyncTask',
  async (data: {
    data_source_id: number;
    sync_type: string;
  }, { rejectWithValue }) => {
    try {
      const result = await dataAPI.createSyncTask(data);
      return result;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '创建同步任务失败');
    }
  }
);

export const fetchSyncStatus = createAsyncThunk(
  'data/fetchSyncStatus',
  async (_, { rejectWithValue }) => {
    try {
      const status = await dataAPI.getSyncStatus();
      return status;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取同步状态失败');
    }
  }
);

const dataSlice = createSlice({
  name: 'data',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    setFilters: (state, action: PayloadAction<{
      search?: string;
      fund_type?: string;
      risk_level?: number;
      min_return?: number;
      max_return?: number;
    }>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    clearFilters: (state) => {
      state.filters = {};
    },
    setPagination: (state, action: PayloadAction<{
      current?: number;
      pageSize?: number;
    }>) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    clearFundSearchResults: (state) => {
      state.fundSearchResults = [];
    },
    clearFundPerformance: (state) => {
      state.fundPerformance = null;
    },
    setCurrentFund: (state, action: PayloadAction<FundData | null>) => {
      state.currentFund = action.payload;
    },
  },
  extraReducers: (builder) => {
    // 获取基金列表
    builder
      .addCase(fetchFunds.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchFunds.fulfilled, (state, action: PayloadAction<PaginatedResponse<FundData>>) => {
        state.loading = false;
        state.funds = action.payload.results;
        state.pagination = {
          ...state.pagination,
          total: action.payload.total_count,
        };
        state.error = null;
      })
      .addCase(fetchFunds.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取基金详情
    builder
      .addCase(fetchFund.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchFund.fulfilled, (state, action: PayloadAction<FundData>) => {
        state.loading = false;
        state.currentFund = action.payload;
        state.error = null;
      })
      .addCase(fetchFund.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 搜索基金
    builder
      .addCase(searchFunds.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchFunds.fulfilled, (state, action: PayloadAction<PaginatedResponse<FundData>>) => {
        state.loading = false;
        state.fundSearchResults = action.payload.results;
        state.error = null;
      })
      .addCase(searchFunds.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取基金业绩
    builder
      .addCase(fetchFundPerformance.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchFundPerformance.fulfilled, (state, action) => {
        state.loading = false;
        state.fundPerformance = action.payload;
        state.error = null;
      })
      .addCase(fetchFundPerformance.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取市场数据
    builder
      .addCase(fetchMarketData.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMarketData.fulfilled, (state, action: PayloadAction<MarketData[]>) => {
        state.loading = false;
        state.marketData = action.payload;
        state.error = null;
      })
      .addCase(fetchMarketData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取市场指标
    builder
      .addCase(fetchMarketIndicators.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMarketIndicators.fulfilled, (state, action) => {
        state.loading = false;
        state.marketIndicators = action.payload;
        state.error = null;
      })
      .addCase(fetchMarketIndicators.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 创建同步任务
    builder
      .addCase(createSyncTask.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createSyncTask.fulfilled, (state) => {
        state.loading = false;
        state.error = null;
      })
      .addCase(createSyncTask.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取同步状态
    builder
      .addCase(fetchSyncStatus.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchSyncStatus.fulfilled, (state, action) => {
        state.loading = false;
        state.syncStatus = action.payload;
        state.error = null;
      })
      .addCase(fetchSyncStatus.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const {
  clearError,
  setFilters,
  clearFilters,
  setPagination,
  clearFundSearchResults,
  clearFundPerformance,
  setCurrentFund,
} = dataSlice.actions;

export default dataSlice.reducer;